<template>
    <div class="common-layout">
        <el-container>
            <el-aside v-if="false" width="200px">{{ asideTitle }}</el-aside>
            <el-container>
                <el-header :style="{ borderRadius: 'var(--el-border-radius-small)' }">
                    {{ headerTitle }}
                    <br>
                    连接到：
                    {{ websocket.url }}
                </el-header>
                <el-main>
                    <message-frame ref="messageFrame" />
                </el-main>
                <el-footer>
                    <div>
                        <!-- <el-icon><Promotion /></el-icon> -->
                        <!-- <el-button :icon="Search" circle /> -->
                        <el-button icon="PictureFilled" type="primary">图片</el-button>
                        <el-button icon="Promotion" @click="sendText" type="success">发送</el-button>
                        <br>
                        <br>
                        <el-input v-model="msgArea" :autosize="{ maxRows: 10 }" type="textarea"
                            placeholder="Please input" />
                    </div>
                </el-footer>
            </el-container>
        </el-container>
    </div>
</template>
  
<script>
import MessageFrame from '../components/MessageFrame.vue'
export default {
    components: { MessageFrame },
    data() {
        return {
            asideTitle: '这是边栏',
            headerTitle:null,
            msgArea: null,
            websocket: null,
        }
    },
    created() {
        if ('WebSocket' in window) {
            this.websocket = new WebSocket("ws://192.168.1.5:8085/socket/room")
            this.websocket.onopen = this.onOpen
            this.websocket.onmessage = this.onMessage
            console.log(this.websocket);
        }else{
            alert('本浏览器不支持websocket')
        }
        
        this.headerTitle=this.getRrsult(10)
        document.title=this.headerTitle
    },
    methods: {
        onOpen() {
            console.log('连接成功：', this.websocket);
        },
        onMessage(event) {
            console.log('收到消息', event);
            this.updateRoomMsg(JSON.parse(event.data))
        },
        sendText() {
            let packet = {
                roomMsgType: '文字',
                RoomMsgId: new Date().getTime(),
                content: this.msgArea,
                timestamp: new Date().getTime(),
                sender:this.headerTitle
            }
            this.websocket.send(JSON.stringify(packet));
            this.msgArea = null
            this.updateRoomMsg(packet)
        },
        updateRoomMsg(packet) {
            this.$refs.messageFrame.receiveRoomMsg(packet)
        },
        getRrsult(n) {
            return Math.random()*n
        }
    }
}
</script>
<style scoped>
.common-layout {
    width: 98vw;
    height: 100vh;
}
</style>